package com.aop;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Component
public class TrackingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 生成唯一的追踪 ID
        String trackingId = UUID.randomUUID().toString();
        // 将追踪 ID 存储到 ThreadLocal 中
        TrackingContext.setTrackingId(trackingId);
        // 在响应头中传递追踪 ID（可选）
        response.setHeader("X-Tracking-Id", trackingId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理 ThreadLocal 中的追踪 ID
        TrackingContext.clear();
    }
}

